#include "ProjectPlugin.h"

#include <QtCore>

#include <juffed/CommandStorage.h>
#include <juffed/Log.h>
#include "ProjectTree.h"

ProjectPlugin::ProjectPlugin() : QObject(), JuffPlugin() {
	tree_ = new ProjectTree();
	menu_ = new QMenu(tr("Project"));
	
	Juff::ActionID ids[] = { Juff::PrjNew, Juff::PrjOpen, Juff::PrjClose, Juff::PrjAddFile, Juff::NullID };
	for (int i = 0; ids[i] != Juff::NullID; i++) {
		if ( ids[i] == Juff::Separator )
			menu_->addSeparator();
		else
			menu_->addAction(CommandStorage::instance()->action(ids[i]));
	}
	
	connect(tree_, SIGNAL(requestOpenFile(const QString&)), SLOT(onFileOpenRequested(const QString&)));

}

void ProjectPlugin::init() {
	connect(api(), SIGNAL(projectFileAdded(Juff::Project*, const QString&)), SLOT(onPrjFileAdded(Juff::Project*, const QString&)));
	connect(api(), SIGNAL(projectFileRemoved(Juff::Project*, const QString&)), SLOT(onPrjFileRemoved(Juff::Project*, const QString&)));
	connect(api(), SIGNAL(projectOpened(Juff::Project*)), SLOT(onPrjOpened(Juff::Project*)));
}

ProjectPlugin::~ProjectPlugin() {
	delete tree_;
}

QString ProjectPlugin::name() const {
	return "Projects";
}

QString ProjectPlugin::targetEngine() const {
	return "all";
}

QString ProjectPlugin::description() const {
	return "";
}

QWidgetList ProjectPlugin::dockList() const {
	QWidgetList wList;
	wList << tree_;
	return wList;
}

QMenu* ProjectPlugin::menu() const {
	return menu_;
}


void ProjectPlugin::onPrjFileAdded(Juff::Project*, const QString&) {
	LOGGER;
	// TODO : do a proper tree update
	tree_->updateTree();
}

void ProjectPlugin::onPrjFileRemoved(Juff::Project*, const QString&) {
	LOGGER;
	// TODO : do a proper tree update
	tree_->updateTree();
}

void ProjectPlugin::onPrjOpened(Juff::Project* prj) {
	LOGGER;
	tree_->setProject(prj);
}

void ProjectPlugin::onFileOpenRequested(const QString& fileName) {
	api()->openDoc(fileName);
}

Q_EXPORT_PLUGIN2(project, ProjectPlugin)
